//
//  BaseDataViewController.m
//  Estate
//
//  Created by wangdongdong on 2017/11/3.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "QianDTableCell.h"
#import "selectBtnCell.h"
#import "PositionTableCell.h"
#import "C_wladdCell_1.h"
#import "B_wuLiaoCell.h"
#import "DefaineCell.h"
#import "ActionSheetDatePicker.h"
#import "OrientationViewController.h"
#import "TableTopStateCell.h"

#import "BaseDataViewController.h"

@interface BaseDataViewController ()<UITableViewDelegate, UITableViewDataSource>

/**发送形式*/
@property (strong, nonatomic) NSArray *sendTypeArr;
/**列表*/
@property(strong, nonatomic)TPKeyboardAvoidingTableView *tableView;
/**施工单位数据源*/
@property (strong, nonatomic) NSDictionary *constructionUnitDic;
/**整改人数据源*/
@property (strong, nonatomic) NSArray *rectificationPeopleArr;
/**时限*/
@property (copy, nonatomic) NSString *limitTime;
/**位置回调数据模型*/
@property (strong, nonatomic) PositionBlockModel *blockModel;
// 当前被点的地址数据模型
@property (strong, nonatomic) AddressModel *addressModel;


@end



@implementation BaseDataViewController

// 发送形式
- (NSArray *)sendTypeArr {
    if (!_sendTypeArr) {
        _sendTypeArr = @[@"工作联系单", @"监理通知单", @"工作暂停令",@"无"];
    }
    return _sendTypeArr;
}

// 列表
- (TPKeyboardAvoidingTableView *)tableView {
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-104)style:UITableViewStyleGrouped];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
        _tableView.showsVerticalScrollIndicator=NO;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
        [_tableView registerClass:[selectBtnCell class] forCellReuseIdentifier:@"sCell"];
        [_tableView registerClass:[PositionTableCell class] forCellReuseIdentifier:@"pCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"C_wladdCell_1" bundle:nil] forCellReuseIdentifier:@"doubleCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
        [_tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"firstCell"];
    }
    return _tableView;
}

// 施工单位数据源
- (NSDictionary *)constructionUnitDic {
    if (!_constructionUnitDic) {
        _constructionUnitDic = [[NSDictionary alloc] init];
    }
    return _constructionUnitDic;
}

// 整改人数据源
- (NSArray *)rectificationPeopleArr {
    if (!_rectificationPeopleArr) {
        _rectificationPeopleArr = [[NSArray alloc] init];
    }
    return _rectificationPeopleArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    // 查询数据
    [self loadData];
}
-(void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chuanzhizhongjian:) name:@"chuanzhizhongjian" object:nil];
}
-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - 查询数据
-(void)loadData {
    // 查找整改人
    self.rectificationPeopleArr = [self getPeopleData:self.recordModel.RECIFY_UNIT];
    // 查找时限
    [self queryProcessByProcessID:self.recordModel.PROCESS_ID];
    // 刷新列表数据
    [self.tableView reloadData];
}

// 通过流程id得到流程时限
- (NSDictionary *)queryProcessByProcessID:(NSString *)processId {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select * from process where id='%@'", processId];
    
    FMResultSet *result = [db executeQuery:sqlStr];
    NSDictionary *dic;
    while ([result next]) {
        dic = [result resultDictionary];
        self.limitTime = DEFISNUL(dic[@"REQUIRED_END_TIME"]);
    }
    [db close];
    return dic;
}


#pragma MARK - UITableViewDelegate,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==0) {
        return 0.001;
        
    }else{
        return 10;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    return view;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section==0) {
        return 7;
    } else if (section==1) {
        return 3;
    } else {
        if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW &&self.recordModel.PROCESS_TYPE ==PROCESS_TYPE_SUPERVISE  ) {
            return 3;
        }else{
            return 5;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        if(row == 0){
            return 30;
        }
        return 44;
    }else if(section==1){
        if(row==0){
            return 44;
        }else{
            return 100;
        }
    }else{
        return 44;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 组
    long section=indexPath.section;
    // 行
    long row=indexPath.row;
    
    if (section==0) {
        if (row == 0) {
            TableTopStateCell *celld = [tableView dequeueReusableCellWithIdentifier:@"firstCell" forIndexPath:indexPath];
            celld.backgroundColor = [UIColor colorWithRed:0.7 green:0.97 blue:0.97 alpha:1.00];
            for (id obj in celld.contentView.subviews) {
                [obj removeFromSuperview];
            }
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake((DEF_SCREEN_WIDTH - 100)/2, 0, 100, 30)];
            [celld.contentView addSubview:btn];
            
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 14, 14)];
            [btn addSubview:imgView];
            imgView.image = [UIImage imageNamed:@"chulizhong"];
            
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 80, 30)];
            [lab setFont:[UIFont systemFontOfSize:12]];
            [btn addSubview:lab];
            if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW) {
                [lab setText:@"状态:待审阅"];
                
            } else if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW_PASS_NO) {
                [lab setText:@"状态:审阅不通过"];
                
            } else if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_CHECK) {
                [lab setText:@"状态:待复查"];
                
            } else if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_CHECK_PASS_YES) {
                [lab setText:@"状态:复查通过"];
                
            } else if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_END) {
                [lab setText:@"状态:结束"];
            }else if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_DOING) {
                [lab setText:@"状态:待执行"];
            }
            return celld;
            
        } else if (row==1) {
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.isedit = NO;
            cell.title.text = @"项  目:";
            cell.textField.text = [LSUtility getProjectNameByProjectId:self.recordModel.PRO_ID][@"PROJECT_NAME"];;
            return cell;
            
        } else if (row==2) {
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
            cell.isedit = NO;
            cell.title.text = @"时  间:";
            cell.textField.text = self.recordModel.CREATE_TIME;
            return cell;
            
        } else if (row==3) {
            selectBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
            if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW &&self.recordModel.PROCESS_TYPE ==PROCESS_TYPE_FOLLOW ) {
                cell.isEdit = YES;
            }
            //设置选中项
            [cell setBtntype:[NSString stringWithFormat:@"%i",self.recordModel.PROBLEM_TYPE]];
            cell.clickXsBlock = ^{
                self.recordModel.PROBLEM_TYPE = PROBLEM_TYPE_SCOUT;
            };
            cell.clickAqBlock=^{
                self.recordModel.PROBLEM_TYPE = PROBLEM_TYPE_SAFE;
            };
            cell.clickqtBlock=^{
                self.recordModel.PROBLEM_TYPE = PROBLEM_TYPE_OTHER;
            };
            cell.clickPzBlock = ^ {
                self.recordModel.PROBLEM_TYPE = PROBLEM_TYPE_SITE;
            };
            return cell;
            
        } else if(row==4) {
            PositionTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW &&self.recordModel.PROCESS_TYPE ==PROCESS_TYPE_FOLLOW ) {
                cell.isEdit = YES;
            }
            
            if (self.addressInfo && ![self.addressInfo isEqualToString:@""]) {
                NSDictionary *dic = [LSUtility dictionaryWithJsonString:self.addressInfo];
                cell.btnStr = [NSString stringWithFormat:@"%@ %@",DEFISNUL(dic[@"address"]),DEFISNUL(dic[@"leftDistanceStr"])];
            } else if (self.recordModel.ADDRES_INFO && ![self.recordModel.ADDRES_INFO isEqualToString:@""]) {
                NSDictionary *dic = [LSUtility dictionaryWithJsonString:self.recordModel.ADDRES_INFO];
                cell.btnStr = [NSString stringWithFormat:@"%@ %@",DEFISNUL(dic[@"address"]),DEFISNUL(dic[@"leftDistanceStr"])];
                
            }
            
            cell.cliclWzBlock = ^{
                OrientationViewController *location=[[OrientationViewController alloc]init];
                location.flagStr = @"jilu";
                
                location.dataArr1 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                location.dataArr2 = [NSMutableArray arrayWithArray:self.blockModel.dataArr2];
                location.dataArr3 = [NSMutableArray arrayWithArray:self.blockModel.dataArr3];
                location.dataArr4 = [NSMutableArray arrayWithArray:self.blockModel.dataArr4];
                location.addressArr = [NSMutableArray arrayWithArray:self.blockModel.addressArr];
                
                location.addressModel = self.addressModel;
                location.aID = self.blockModel.aID;
                location.firstID = self.blockModel.firstID;
                location.secondID = self.blockModel.secondID;
                location.thirdID = self.blockModel.thirdID;
                
                location.keyStr = self.blockModel.keyStr;
                location.number = self.blockModel.number;
                location.position = self.blockModel.position;
                location.scale = self.blockModel.scale;
                
                if (self.addressInfo) {
                    NSDictionary *dic = [LSUtility dictionaryWithJsonString:self.addressInfo];
                    CGFloat x = [dic[@"long"] floatValue];
                    CGFloat y = [dic[@"lat"] floatValue];
                    location.selectedX=x;
                    location.selectedY=y;
                }else if (self.recordModel.ADDRES_INFO) {
                    NSDictionary *dic = [LSUtility dictionaryWithJsonString:  self.recordModel.ADDRES_INFO];
                    CGFloat x = [dic[@"long"] floatValue];
                    CGFloat y = [dic[@"lat"] floatValue];
                    location.selectedX=x;
                    location.selectedY=y;
                }
                
                if (self.recordModel.ADDRESS_ID) {
                    location.number = 2;
                }
                
                if (location.number) {
                    location.hC = YES;
                    location.aID = self.recordModel.ADDRESS_ID;
                }
                
                [self.navigationController pushViewController:location animated:YES];
                
                // 回传位置值
                location.returnPlaceInfoBlock = ^(PositionBlockModel *model, AddressModel *addModel, NSString *addInfoStr) {
                    self.addressModel = addModel;
                    self.blockModel = model;
                    self.recordModel.ADDRES_INFO = addInfoStr;
                    self.recordModel.ADDRESS_ID = model.aID;
                    self.addressInfo = addInfoStr;
                    // 刷新位置值
                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:5 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                };
            };
            return cell;
            
        } else if (row==5) {
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath];
            cell.title.text=@"发送形式:";
            cell.text.text = self.sendTypeArr[self.recordModel.SEND_TYPE - 1];
            return cell;
            
        } else {
            C_wladdCell_1 *cell=[tableView dequeueReusableCellWithIdentifier:@"doubleCell" forIndexPath:indexPath];
            cell.line.hidden = YES;
            cell.leftConstraint.constant = 0.;
            cell.text1.userInteractionEnabled = NO;
            cell.text2.userInteractionEnabled = NO;
            cell.title1.text=@"记录人:";
            cell.title2.text=@"负责人:";
            
            // 记录人
            if (self.recordModel.PROCESS_ID && ![self.recordModel.PROCESS_ID isEqualToString:@""]) {
                NSDictionary *dic=[self queryProcessByProcessID:self.recordModel.PROCESS_ID];
                cell.text1.text = [LSUtility getuserIdByUserName:dic[@"PROCESS_PUBLISHERS"]][@"REAL_NAME"];
                //                cell.text1.text = [LSUtility getuserIdByUserName:self.recordModel.RECORD_USER][@"REAL_NAME"];
            }
            // 负责人
            if (self.recordModel.RECORD_MASTER && ![self.recordModel.RECORD_MASTER isEqualToString:@""]) {
                cell.text2.text = [LSUtility getuserIdByUserName:self.recordModel.RECORD_MASTER][@"REAL_NAME"];
            }
            return cell;
        }
    } else if (section==1) {
        if (row==0) {
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.title.text = @"标  题:";
            if (self.recordModel.PROCESS_TITLE && ![self.recordModel.PROCESS_TITLE isEqualToString:@""]) {
                cell.textField.text = self.recordModel.PROCESS_TITLE;
                
            } else {
                cell.textField.placeholder = @"请输入标题";
            }
            if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW &&self.recordModel.PROCESS_TYPE ==PROCESS_TYPE_FOLLOW ) {
                cell.isedit = YES;
            }else{
                cell.isedit = NO;
                
            }
            cell.textValueChangedBlock = ^(NSString *valueStr){
                self.recordModel.PROCESS_TITLE = valueStr;
            };
            return cell;
            
        } else if(row==1) {
            B_wuLiaoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.title.text = @"描  述:";
            cell.text.text = DEFISNUL(self.recordModel.PROCESS_CONTENT);
            if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW &&self.recordModel.PROCESS_TYPE ==PROCESS_TYPE_FOLLOW ) {
                cell.isEdit = YES;
            }else{
                cell.isEdit = NO;
            }
            cell.textValueChangedBlock = ^(NSString *valueStr){
                self.recordModel.PROCESS_CONTENT = valueStr;
            };
            return cell;
            
        } else {
            B_wuLiaoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.title.text = @"要  求:";
            cell.text.text = DEFISNUL(self.recordModel.PROCESS_REQUIRED);
            if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW &&self.recordModel.PROCESS_TYPE ==PROCESS_TYPE_FOLLOW ) {
                cell.isEdit = YES;
            }else{
                cell.isEdit = NO;
            }
            cell.textValueChangedBlock = ^(NSString *valueStr){
                self.recordModel.PROCESS_REQUIRED = valueStr;
            };
            return cell;
        }
    } else {
        DefaineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath];
        cell.line.hidden = YES;
        if (row == 0) {
            cell.title.text=@"时  限:";
            cell.text.text = self.limitTime ? self.limitTime : @"请选择";
            return cell;
            
        } else if(row == 1){
            cell.title.text=@"严重度:";
            cell.text.text = self.recordModel.SEVERITY ? self.recordModel.SEVERITY : @"请选择";
            return cell;
            
        } else if (row == 2) {
            cell.title.text=@"发送时间:";
            cell.text.text= self.recordModel.SEND_TIME ? self.recordModel.SEND_TIME : @"请选择";
            return cell;
            
        } else if(row == 3) {
            cell.title.text=@"负责单位:";
            NSDictionary *dic = [LSUtility getUnitNameByUnitId:self.recordModel.RECIFY_UNIT];
            cell.text.text = DEFISNUL(dic[@"PRO_UNIT_NAME"]);
            return cell;
            
        } else {
            cell.title.text=@"整改人:";
            NSString *changeStr;
            if (self.recordModel.RECIFY_USER && ![self.recordModel.RECIFY_USER isEqualToString:@""]) {
                changeStr = [LSUtility getuserIdByUserName:self.recordModel.RECIFY_USER][@"REAL_NAME"];
            }
            cell.text.text = changeStr ? changeStr : @"请选择";
            return cell;
        }
    }
}

/*
 *点击方法
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    long section=indexPath.section;
    long row=indexPath.row;
    DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSNumber *ninit = [NSNumber numberWithInteger:0];
    
    if (self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW&&self.recordModel.PROCESS_TYPE == PROCESS_TYPE_FOLLOW) {
        // 发送形式
        if(section == 0){
            if (row == 5) {
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[self.sendTypeArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                    
                    // 得到选择下标
                    int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                    // 记录选择类型
                    if (iv == 0) {
                        self.recordModel.SEND_TYPE = SEND_TYPE_CONTACTLIST;
                        
                    } else if (iv == 1) {
                        self.recordModel.SEND_TYPE = SEND_TYPE_SUPERVISIONNOTICE;
                        
                    } else if (iv == 2) {
                        self.recordModel.SEND_TYPE = SEND_TYPE_STOPLIST;
                    }
                    cell.text.text = self.sendTypeArr[iv];
                    
                } cancelBlock:nil origin:self.view];
            }
        } if (section == 2) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *curDate = [NSDate date];
            
            if (row == 0) {   // 时限
                ActionSheetDatePicker *picker = [[ActionSheetDatePicker alloc] initWithTitle:nil datePickerMode:UIDatePickerModeDateAndTime selectedDate:curDate doneBlock:^(ActionSheetDatePicker *picker, NSDate *selectedDate, id origin) {
                    
                    NSString *strDate = [dateFormatter stringFromDate:selectedDate];
                    cell.text.text = strDate;
                    self.limitTime = strDate;
                    
                } cancelBlock:nil origin:self.view];
                picker.minimumDate = curDate;
                [picker showActionSheetPicker];
                
            } else if (row == 2) {  // 发送时间
                ActionSheetDatePicker *picker = [[ActionSheetDatePicker alloc] initWithTitle:nil datePickerMode:UIDatePickerModeDateAndTime selectedDate:curDate doneBlock:^(ActionSheetDatePicker *picker, NSDate *selectedDate, id origin) {
                    
                    NSString *strDate = [dateFormatter stringFromDate:selectedDate];
                    cell.text.text = strDate;
                    self.recordModel.SEND_TIME = strDate;
                    
                } cancelBlock:nil origin:self.view];
                picker.minimumDate = curDate;
                [picker showActionSheetPicker];
                
            } else if (row == 3) {      // 负责单位
                // 获取施工单位数据
                self.constructionUnitDic = [self getUnitData];
                NSArray *unitArr = self.constructionUnitDic[@"nameArr"];
                if (unitArr.count > 0) {
                    [ActionSheetStringPicker showPickerWithTitle:nil rows:@[unitArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                        //得到选择下标
                        int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                        cell.text.text = unitArr[iv];
                        
                        // 获取整改人数据
                        NSArray *IDArr = self.constructionUnitDic[@"IDArr"];
                        self.recordModel.RECIFY_UNIT = IDArr[iv];
                        self.rectificationPeopleArr = [self getPeopleData:self.recordModel.RECIFY_UNIT];
                        
                        // 刷新整改人cell
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:4 inSection:2];
                        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                        
                    } cancelBlock:nil origin:self.view];
                    
                } else {
                    [LSUtility showToastWithMessage:@"无可选择项" inView:self.navigationController.view Andtime:1.];
                }
            } else if (row == 4) {  //整改人
                if (!self.recordModel.RECIFY_UNIT) {
                    [LSUtility showToastWithMessage:@"请先选择整改单位" inView:self.view Andtime:1.];
                    
                } else {
                    NSMutableArray *nameArr = [NSMutableArray array];
                    for (int i = 0; i < self.rectificationPeopleArr.count; i++) {
                        NSString *name = [LSUtility getuserIdByUserName:self.rectificationPeopleArr[i]][@"REAL_NAME"];
                        
                        if (name) {
                            [nameArr addObject:name];
                        }
                    }
                    if (nameArr.count > 0) {
                        [ActionSheetStringPicker showPickerWithTitle:nil rows:@[nameArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                            //得到选择下标
                            int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                            NSString *userID = self.rectificationPeopleArr[iv];
                            self.recordModel.RECIFY_USER = userID;
                            cell.text.text = [LSUtility getuserIdByUserName:userID][@"REAL_NAME"];
                            
                        } cancelBlock:nil origin:self.view];
                        
                    } else {
                        [LSUtility showToastWithMessage:@"无可选择项" inView:self.navigationController.view Andtime:1.];
                    }
                }
            } else if (row == 1){   // 严重度
                NSArray *arr = @[@"一般",@"严重"];
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[arr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                    //得到选择下标
                    int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                    cell.text.text = arr[iv];
                    self.recordModel.SEVERITY = arr[iv];
                    
                } cancelBlock:nil origin:self.view];
            }
        }
    }
}

/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

// 获取整改单位数据
- (NSMutableDictionary *)getUnitData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *proID = DEF_PERSISTENT_GET_OBJECT(@"proid");
    NSString *sql = [NSString stringWithFormat:@"SELECT PRO_UNIT_NAME, ID FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_02'", proID];
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *unitNameArr = [NSMutableArray array];
    NSMutableArray *IDArr = [NSMutableArray array];
    NSMutableDictionary *unitDic = [NSMutableDictionary dictionary];
    while ([result next]) {
        NSString *unitName = [result stringForColumn:@"PRO_UNIT_NAME"];
        NSString *ID = [result stringForColumn:@"ID"];
        [unitNameArr addObject:unitName];
        [IDArr addObject:ID];
    }
    [db close];
    [unitDic setObject:unitNameArr forKey:@"nameArr"];
    [unitDic setObject:IDArr forKey:@"IDArr"];
    return unitDic;
}

// 获取整改人数据
- (NSMutableArray *)getPeopleData:(NSString *)ID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT USER_ID FROM PROJECT_USER WHERE UNIT_ID = '%@' AND (USER_TYPE = 'CONSTRACT_01' OR USER_TYPE = 'CONSTRACT_02' OR USER_TYPE = 'CONSTRACT_03' OR USER_TYPE = 'CONSTRACT_04' OR USER_TYPE = 'CONSTRACT_05' OR USER_TYPE = 'CONSTRACT_06' OR USER_TYPE = 'CONSTRACT_07')", ID];
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *nameArr = [NSMutableArray array];
    while ([result next]) {
        NSString *userID = [result stringForColumn:@"USER_ID"];
        [nameArr addObject:userID];
    }
    [db close];
    nameArr = [nameArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
    return nameArr;
}

// 插入数据
- (void)chuanzhizhongjian:(NSNotification *)text {
    
    if (self.recordModel.PROBLEM_TYPE == 0) {
        [LSUtility showToastWithMessage:@"请选择问题类型" inView:self.navigationController.view Andtime:1.];
        return;
    }
    
    if (self.recordModel.ADDRESS_ID && [self.recordModel.ADDRESS_ID isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请选择位置" inView:self.navigationController.view Andtime:1.];
        return;
    }
    
    if (self.recordModel.SEND_TYPE == 0) {
        [LSUtility showToastWithMessage:@"请选择发送形式" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if (!self.recordModel.RECORD_MASTER || [self.recordModel.RECORD_MASTER isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请选择负责人" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if (!self.recordModel.PROCESS_TITLE || [self.recordModel.PROCESS_TITLE isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请填写标题" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if (!self.recordModel.PROCESS_CONTENT || [self.recordModel.PROCESS_CONTENT isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请填写描述" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if (!self.recordModel.PROCESS_REQUIRED || [self.recordModel.PROCESS_REQUIRED isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请填写要求" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if (!self.limitTime || [self.limitTime isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请选择时限" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if (!self.recordModel.SEVERITY || [self.recordModel.SEVERITY isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请选择严重度" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if(self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW &&self.recordModel.PROCESS_TYPE ==PROCESS_TYPE_SUPERVISE ){
        
    }else if (!self.recordModel.RECIFY_UNIT || [self.recordModel.RECIFY_UNIT isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请选择整改单位" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if(self.recordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW &&self.recordModel.PROCESS_TYPE ==PROCESS_TYPE_SUPERVISE ){
        
    }else if (!self.recordModel.RECIFY_USER || [self.recordModel.RECIFY_USER isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请选择整改人" inView:self.navigationController.view Andtime:1.];
        return;
    }
    
    NSDictionary *imageDic = text.userInfo;
    // 更新流程表
    [self updateProcess:imageDic[@"PROCESS_STAGE"]];
    // 添加流程记录
    [self addProcessRecordData:imageDic];
    // 刷新总监督办列表
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDuBList" object:nil];
    // 通知首页刷新数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"home" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

// 修改流程表
- (void)updateProcess:(NSString *)processStr {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 流程结束时间
    NSString *endTime;
    if ([processStr integerValue] == PROCESS_STAGE_REVIEW_PASS_NO) {
        endTime = [LSUtility nowTime];
        
    } else {
        endTime = @"";
    }
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic = @{
                   @"ADDRESS_ID":DEFISNUL(self.recordModel.ADDRESS_ID),
                   @"ADDRES_INFO":DEFISNUL(self.addressInfo),
                   @"PROCESS_STAGE":processStr,
                   @"PROCESS_RECIFY_USERS":DEFISNUL(self.recordModel.RECIFY_USER),
                   @"PROCESS_RECIFY_UNITS":DEFISNUL(self.recordModel.RECIFY_UNIT),
                   @"RECIFY_REVIEW_USERS":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                   @"BEGIN_TIME":DEFISNUL(self.recordModel.SEND_TIME),
                   @"REQUIRED_END_TIME":DEFISNUL(self.limitTime),
                   @"END_TIME":endTime,
                   @"PROCESS_TITLE":DEFISNUL(self.recordModel.PROCESS_TITLE),
                   @"EXTEND_INFO":@"",
                   @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                   @"MODIFY_IP":DEFISNUL([LSUtility getIPAddress]),
                   @"MODIFY_TIME":DEFISNUL([LSUtility nowTime]),
                   @"LOCAL_MODIFY_STATE":@"MOD",
                   };
    [dbhelper DataBase:db updateTable:PROCESS setKeyValues:pragameDic whereCondition:@{@"id":self.recordModel.PROCESS_ID}];
}

#pragma mark - 新增流程记录表
- (void)addProcessRecordData:(NSDictionary *)parameDic {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper=[DBHelper help];
    // 审核状态parameDic[@"PROCESS_STAGE"]
    NSString *reviewStateStr;
    if ([parameDic[@"PROCESS_STAGE"] isEqualToString:@"202"]) {
        reviewStateStr = @"2";
    } else {
        reviewStateStr = @"1";
    }
    // 字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":DEFISNUL(parameDic[@"ID"]),
                 @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                 @"PROCESS_ID":DEFISNUL(self.recordModel.PROCESS_ID),
                 @"WEATHER":@"",
                 @"ADDRESS_ID":DEFISNUL(self.recordModel.ADDRESS_ID),
                 @"ADDRES_INFO":DEFISNUL(self.addressInfo),
                 @"PROCESS_TYPE":[NSString stringWithFormat:@"%d", PROCESS_TYPE_FOLLOW],
                 @"PROCESS_STAGE":DEFISNUL(parameDic[@"PROCESS_STAGE"]),
                 @"RECORD_USER":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"PROBLEM_TYPE":[NSString stringWithFormat:@"%d", self.recordModel.PROBLEM_TYPE],
                 @"RECORD_MASTER":DEFISNUL(self.recordModel.RECORD_MASTER),
                 @"RECIFY_USER":DEFISNUL(self.recordModel.RECIFY_USER),
                 @"RECIFY_UNIT":DEFISNUL(self.recordModel.RECIFY_UNIT),
                 @"SEVERITY":DEFISNUL(self.recordModel.SEVERITY),
                 //三期bug解决 endtime为@""新增为空
                 @"END_TIME":@"",
                 //三期bug解决 endtime为@""新增为空
                 @"SEND_TIME":DEFISNUL(self.recordModel.SEND_TIME),
                 @"SEND_TYPE":[NSString stringWithFormat:@"%d", self.recordModel.SEND_TYPE],
                 @"PROCESS_TITLE":DEFISNUL(self.recordModel.PROCESS_TITLE),
                 @"PROCESS_CONTENT":DEFISNUL(self.recordModel.PROCESS_CONTENT),
                 @"PROCESS_REQUIRED":DEFISNUL(self.recordModel.PROCESS_REQUIRED),
                 @"PROCESS_DESC":@"",
                 @"SUBMITTORS":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"PUT_USER":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"REVIEW_USER":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"REVIEW_OPINION":DEFISNUL(parameDic[@"REVIEW_OPINION"]),
                 @"REVIEW_STATE":reviewStateStr,
                 @"FILEINFOS":DEFISNUL(parameDic[@"ARRAY"]),
                 @"EXTEND_INFO":@"",
                 @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"CREATE_TIME":DEFISNUL([LSUtility nowTime]),
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_USER_NAME":@"",
                 @"MODIFY_IP":@"",
                 @"MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_USER_NAME":@"",
                 @"LOCAL_MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:PROCESS_RECORD];
    if(isAdd){
        NSLog(@"流程记录新增成功");
        
    }else{
        NSLog(@"流程记录新增失败");
    }
}


@end

